import ash from '@ash.ts/ash';
import { EntityCreator } from '../util/EntityCreator';
import { AsteroidCollisionNode, GameNode, WaitForStartNode } from '../data/nodes';

export class WaitForStartSystem extends ash.System {
    private _creator: EntityCreator;

    private _gameNodes: ash.NodeList<GameNode> | null = null;

    private _waitNodes: ash.NodeList<WaitForStartNode> | null = null;

    private _asteroids: ash.NodeList<AsteroidCollisionNode> | null = null;

    public constructor(creator: EntityCreator) {
        super();
        this._creator = creator;
    }

    public addToEngine(engine: ash.Engine): void {
        this._waitNodes = engine.getNodeList(WaitForStartNode);
        this._gameNodes = engine.getNodeList(GameNode);
        this._asteroids = engine.getNodeList(AsteroidCollisionNode);
    }

    public update(time: number): void {
        if (!this._waitNodes || !this._gameNodes || !this._asteroids) {
            return;
        }

        const waitForStartNode: WaitForStartNode | null = this._waitNodes.head;
        const game: GameNode | null = this._gameNodes.head;
        if (waitForStartNode && waitForStartNode.wait.startGame && game) {
            for (let asteroid: AsteroidCollisionNode | null = this._asteroids.head; asteroid; asteroid = asteroid.next) {
                if (asteroid.entity) {
                    this._creator.destroyEntity(asteroid.entity);
                }
            }

            game.state.setForStart();
            waitForStartNode.wait.startGame = false;
            if (waitForStartNode.entity) {
                this._creator.destroyEntity(waitForStartNode.entity);
            }
        }
    }

    public removeFromEngine(engine: ash.Engine): void {
        this._gameNodes = null;
        this._waitNodes = null;
        this._asteroids = null;
    }
}
